package com.handsome.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.handsome.controller.consts.CommonConst;
import com.handsome.dto.BootstrapDataTableDto;
import com.handsome.entity.HsWidget;
import com.handsome.service.DictionaryService;
import com.handsome.service.WidgetService;
import com.handsome.utils.ClassScaner;
import com.handsome.utils.Result;
import com.handsome.utils.ResultGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

@Controller
public class FormController extends BaseController {

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private WidgetService widgetService;

    @RequestMapping("/form/index")
    public String index(Model model) {
       /* HsWidget formById = widgetService.getFormById(22);
        ObjectMapper objectMapper = new ObjectMapper();
        String classPackage = "com.handsome.service.";
        try {
            List list = objectMapper.readValue(formById.getFields(), ArrayList.class);
            WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();

            list.forEach(e->{
                HashMap<String, Object> map = (HashMap<String, Object>) e;
                String source = (String) map.get("source");
                if(!StringUtils.isBlank(source)){
                    String[] strings = source.split("\\.");
                    String className = strings[0];
                    String methods = strings[1];
                    try {
                        Class aClass = Class.forName(classPackage + className);
                        Class  cls = wac.getBean(aClass).getClass();
                        Method method = cls.getDeclaredMethod(methods);
                        Object invoke = Collections.singletonList(method.invoke(wac.getBean(aClass)));
                        if(invoke != null){
                            System.out.println("*************************");
                            map.put("data",invoke);

                            System.out.println("*************************");
                        }

                    } catch (ClassNotFoundException | NoSuchMethodException   | IllegalAccessException | InvocationTargetException e1) {
                        e1.printStackTrace();
                    }
                }
            });
            System.out.println(list);

            model.addAttribute("widgets", list);
        } catch (IOException e) {
            e.printStackTrace();
        }
        formById.getFields();*/


        // 获取控件的类型
        model.addAttribute("widgetTypes", dictionaryService.getDictionaryById(CommonConst.WIDGET_TYPE_ID));
        model.addAttribute("mappingEntityItems", ClassScaner.getClassNames("com.handsome.entity"));
        return "form/index";
    }

    /**
     * 创建表单字段
     *
     * @param model 视图
     * @param pid   字典项id
     * @return View
     */

    @RequestMapping("/form/create_field")
    public String createField(Model model, @RequestParam("pid") Integer pid) {
        try {
            Class aClass = Class.forName("com.handsome.service.DictionaryService");
            WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
            Class<?> cls = wac.getBean(aClass).getClass();
            Method m = cls.getDeclaredMethod("getDictionaryById", Integer.class);
            Object o = m.invoke(wac.getBean(aClass), 24);

        } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

        HashMap<String, Object> attrs = new HashMap<>();
        attrs.put("widgetAttr", dictionaryService.getDictionaryById(pid));
        attrs.put("rules", dictionaryService.getDictionaryById(CommonConst.FORM_VALIDATE_ID));
        List<String> classNames = ClassScaner.getClassNames(CommonConst.SOURCE_PACKAGE);
        List<String> disposeClassNames = new ArrayList<>();
        for (String className : classNames) {
            disposeClassNames.add(className.substring(className.lastIndexOf('.') + 1));
        }
        attrs.put("classItems", disposeClassNames);
        model.addAllAttributes(attrs);

        return "form/create_field";
    }

    /**
     * 根据class获取该class下的方法
     *
     * @param className 类型
     * @return Result
     */
    @PostMapping("/form/get_methods_by_class")
    @ResponseBody
    public Result<Object> getMethodsByClass(@RequestParam("class_name") String className) {
        return ResultGenerator.genSuccessResult(ClassScaner.getMethodsByClass(CommonConst.SOURCE_PACKAGE + '.' + className));
    }

    /**
     * 根据方法获取该方法下的参数类型
     *
     * @param className  类名
     * @param methodName 方法名
     * @return Result
     */
    @PostMapping("/form/get_params_by_method")
    @ResponseBody
    public Result getParamsByMethod(@RequestParam("class_name") String className, @RequestParam("method_name") String methodName) {
        return ResultGenerator.genSuccessResult(ClassScaner.getParamsByMethod(CommonConst.SOURCE_PACKAGE + '.' + className, methodName));
    }


    /**
     * 创建表单
     *
     * @param widget 表单信息
     * @return Result
     */
    @PostMapping("/form/build_form")
    @ResponseBody
    public Result buildForm(HsWidget widget) {

        return widgetService.buildForm(widget);
    }

    /**
     * 获取表单列表
     *
     * @return BootstrapDataTableDto
     */
    @GetMapping("/form/get_form_list")
    @ResponseBody
    public BootstrapDataTableDto getFormList() {

        return widgetService.getFormList();
    }

    /**
     * 预览表单
     *
     * @param model 视图
     * @return View
     */
    @RequestMapping("/form/preview_form")
    public String previewForm(Model model, HttpServletRequest request, @RequestParam("form_id") Integer formId) {

        // 获取该表单的信息
        HsWidget formInfo = widgetService.getFormById(formId);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 获取字段信息
            List formFields = objectMapper.readValue(formInfo.getFields(), ArrayList.class);
            WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
            formFields.forEach(e -> {
                HashMap<String, Object> map = (HashMap<String, Object>) e;
                reflectionCall(request, wac, map);
            });
            model.addAttribute("widgets", formFields);
            model.addAttribute("formData", formInfo);
            model.addAttribute("btnLabel", "模拟操作");
            model.addAttribute("submit", false);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "form/form_tpl";
    }


}
